import includes from './include.js';
import excludes from './exclude.js';

const mockTarget = import.meta.env.VITE_MOCK_TARGET;
const enableMock = import.meta.env.VITE_MOCK === 'true';
const enabledUrlMode = import.meta.env.VITE_MOCK_URL_MODE === 'true';
const isIncludeMode = import.meta.env.VITE_MOCK_INCLUDE !== 'false';

/**
 * Mock处理器
 *
 * 使用方式
 * 1. 创建一个实例
 * 2. 调用实例的process方法
 *
 * 示例
 * let mockProcessor = new MockProcessor({
 *     axiosRequestConfig: axiosRequestConfig,
 * });
 * mockProcessor.process();
 */
class MockProcessor {
  /**
   * @param options {object}
   * {
   *   axiosRequestConfig（必填）{object}: AxiosRequestConfig对象
   *   match（选填）{boolean function()}: 全局前置过滤器，返回true则该请求被mock，返回false则该请求不被mock。优先级最低
   * }
   */
  constructor(options) {
    this.options = options;
  }
  get axiosRequestConfig() {
    return this.options.axiosRequestConfig;
  }
  get match() {
    const isFunction = typeof this.options.match === 'function';
    if (isFunction) {
      return this.options.match;
    }
    return () => true;
  }
  
  process() {
    if (!this.checkIsNeedMock()) { return; }
    
    if (!mockTarget) {
      throw RangeError('VITE_MOCK_TARGET环境变量为空');
    }
    
    this.axiosRequestConfig.url = mockTarget + this.axiosRequestConfig.url;
  }
  
  checkIsNeedMock() {
    if (!enableMock) { return false; }
    
    // 如果是url模式，是否开启还得看mock参数的值
    if (enabledUrlMode) {
      const searchParams = new URLSearchParams(window.location.search);
      const mock = searchParams.get('mock');
      
      if (mock !== 'true') {
        return false;
      }
    }
    
    // mock=true 或 没有启用url模式
    
    // 检查url是否需要被mock
    const url = this.axiosRequestConfig.url;
    
    const cludeList = isIncludeMode ? includes : excludes;
    let isMatch = false;
    for (const item of cludeList) {
      if (!this.checkUrlIsMatchApiListItem(url, item)) {
        continue;
      }
      isMatch = true;
      break;
    }
    
    // 如果是include模式，不匹配说明不需要mock，匹配说明需要mock
    if (isIncludeMode) {
      return isMatch;
    }
    
    // 如果是exclude模式，匹配说明不需要mock，不匹配说明需要mock
    return !isMatch;
  }
  
  checkUrlIsMatchApiListItem(url, item) {
    // 字符串
    if (typeof item === 'string') {
      if (url !== item) {
        return false;
      }
      
      return this.match(); // 通过get获取后()执行
    }
    
    // 对象
    if (typeof item !== 'object') {
      return false;
    }
    
    if (item?.url !== url) {
      return false;
    }
    
    // 如果有指定匹配方式
    if (typeof item.match === 'function') {
      return item.match();
    }
    
    // 如果没有指定匹配方式，则使用全局默认匹配
    return this.match(); // 通过get获取后()执行
  }
}

export default MockProcessor;